package com.bening.smsapp.parser;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import com.bening.smsapp.bean.FileSource;
import com.bening.smsapp.bootstrap.BootConfigParameters;
import com.bening.smsapp.constant.PropertiesConstant;
import com.bening.smsapp.constant.SmsAppConstant;
import com.bening.smsapp.dao.SmsAppDao;
import com.bening.smsapp.factory.SmsAppFactory;
import com.bening.smsapp.util.SmsAppTools;
import com.bening.smsapp.parser.thread.*;

public class ParserEngine {

	private static BootConfigParameters bootParam = BootConfigParameters.getInstance();
	final static Logger logger = Logger.getLogger( ParserEngine.class );
	private static SmsAppDao smsDao = SmsAppFactory.getDaoObject();
	private static ThreadPool pool = new ThreadPool(new ThreadObjectFactory());
	
	public static void process(BootConfigParameters params) {
			
			
	        String sql = bootParam.getQueryProperties().getProperty(PropertiesConstant.SQL_SELECT_TOBE_PARSED);
	        
	        PreparedStatement prepStmt = null;
	        Connection conn;
	        ResultSet rs = null;
	        conn = SmsAppFactory.getDbConnection();
	        int sourcePath = 0;
	        try
	        {
	            prepStmt = conn.prepareStatement( sql );
	            rs = prepStmt.executeQuery();

	            boolean more = rs.next();
	            if( more )
	            {
	                while( more )
	                {
	                    FileSource f = new FileSource();
	                    f.setFileName(rs.getString("FILENAME"));
	                    f.setCdrType(rs.getInt("CDR_TYPE"));
	                    f.setLocalFilePath(rs.getString("LOCAL_FILEPATH"));
	                    f.setSourcePathId(rs.getInt("SOURCEPATH_ID"));
	                    if ( logger.isInfoEnabled() )
	                    {
	                        logger.info( Thread.currentThread().getName() +"-BEGIN: begin parsing file " + f.getFileName() );
	                    }
	                    // ASCII
	                    //if(f.getCdrType() == SmsAppConstant.ASCII)
	                    	//parseAscii(f);
	                    runParse(f.getCdrType(), f.getLocalFilePath(), f.getFileName(), f.getSourcePathId());
	                    // ASN1
//	                    else if(f.getCdrType() == SmsAppConstant.ASN1)
//	                    	parseAsn1(f);
	                    
	                    if ( logger.isInfoEnabled() )
	                    {
	                        logger.info( Thread.currentThread().getName() +"-END: done parsing file " + f.getFileName() );
	                    }

	                    more = rs.next();
	                }
	            }
	            else
	            {
	                if ( logger.isInfoEnabled() )
	                {
	                    logger.info( Thread.currentThread().getName()  + "-no files to parse." );
	                }
	            }
	        }
	        catch ( SQLException e )
	        {
	            logger.error( Thread.currentThread().getName()  + e.getClass() + ": " + e.getMessage() + ": while retrieving filenames to be parsed." );
	            SmsAppTools.InsertEventLog(SmsAppConstant.SQL_ERROR, e.getMessage(), sourcePath);
	        }
	        finally
	        {
	            try
	            {
	                if( rs != null )
	                {
	                    rs.close();
	                }
	                if( prepStmt != null )
	                {
	                    prepStmt.close();
	                }
	                if ( conn != null )
	                {
	                    conn.close();
	                }
	            }
	            catch ( SQLException e )
	            {
	                logger.error( Thread.currentThread().getName() + e.getClass() +  ": " + e.getMessage(), e );
	            }
	        }

	}
/*	
 * @deprecated
	private static void parseAscii(FileSource f) {
		
		logger.info(f.getFileName()+" has type ASCII");
		AsciiParser.parseFileToDatabase(f.getLocalFilePath(), f.getFileName(), f.getSourcePathId());
	}
	
	private static void parseAsn1(FileSource f) {
		logger.info(f.getFileName()+" has type ASN1");
		Asn1Parser.parseFileToDatabase(f.getLocalFilePath(), f.getFileName(), f.getSourcePathId());
	}*/
	
	private static void runParse(int type, String localPath, String fileName, int sourcePath) {
		try {
	         WorkerThread rt = (WorkerThread) pool.borrowObject();
	         rt.setPool(pool); 
	         rt.execute(type, localPath, fileName, sourcePath);
	      } catch (Exception e) {
	         logger.error("", e);
	      }
	}
}
